package com.bawei.module_live.version2.danmu

import com.neovisionaries.ws.client.WebSocket
import com.neovisionaries.ws.client.WebSocketAdapter
import com.neovisionaries.ws.client.WebSocketFactory
import org.json.JSONObject

class DanmakuWebSocketClient(
    private val wsUrl: String,
    private val onDanmakuReceived: (text: String, color: Int) -> Unit
) {
    private var webSocket: WebSocket? = null

    fun connect() {
        android.util.Log.d("DanmakuWS", "Connecting to $wsUrl")
        webSocket = WebSocketFactory()
            .createSocket(wsUrl)
            .addListener(object : WebSocketAdapter() {
                override fun onConnected(websocket: WebSocket, headers: Map<String, List<String>>) {
                    android.util.Log.d("DanmakuWS", "WebSocket connected: $wsUrl")
                }
                override fun onTextMessage(websocket: WebSocket, message: String) {
                    android.util.Log.d("DanmakuWS", "Received message: $message")
                    // 解析服务器推送的弹幕消息
                    val json = JSONObject(message)
                    if (json.optInt("type") == 1) {
                        val text = json.optString("content", "")
                        val color = try {
                            android.graphics.Color.parseColor(json.optString("fontcolor", "#FFFFFF"))
                        } catch (e: Exception) {
                            android.util.Log.e("DanmakuWS", "Color parse error", e)
                            android.graphics.Color.WHITE
                        }
                        android.util.Log.d("DanmakuWS", "Trigger onDanmakuReceived: $text, color: $color")
                        onDanmakuReceived(text, color)
                    } else {
                        android.util.Log.d("DanmakuWS", "Non-danmaku message received, type: ${json.optInt("type")}")
                    }
                }
                 fun onDisconnected(websocket: WebSocket, code: Int, reason: String?, remote: Boolean) {
                    android.util.Log.d("DanmakuWS", "WebSocket disconnected: $reason")
                }
                 fun onError(websocket: WebSocket, cause: Exception) {
                    android.util.Log.e("DanmakuWS", "WebSocket error", cause)
                }
            })
            .connectAsynchronously()
    }

    fun sendDanmaku(text: String, color: String = "#00f0ff", itemid: String, userid: String) {
        val json = JSONObject().apply {
            put("type", 1)
            put("content", text)
            put("fontcolor", color)
            put("itemid", itemid)
            put("userid", userid)
            put("createtime", System.currentTimeMillis())
        }
        android.util.Log.d("DanmakuWS", "Sending danmaku: $json")
        webSocket?.sendText(json.toString()) ?: android.util.Log.e("DanmakuWS", "WebSocket is null when sending")
    }

    fun disconnect() {
        android.util.Log.d("DanmakuWS", "Disconnecting WebSocket")
        webSocket?.disconnect()
    }
}